#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)
#define MAX 1024

class fifo
{
public:
    fifo(std::string path, std::string name)
        : _path(path)
        , _name(name)
    {
        _pathname = _path + _name;
    }

    void Creat()
    {
        umask(000);
        int ret = mkfifo(_pathname.c_str() , 0666);
        if(ret == 0)
        {
             ERR_EXIT("mkfifo: ");
        }
        else
        {
           std::cout << "命名管道创建成功 " << std::endl;
        }
    }

    void Read()
    {
        char buffer [MAX] ;
        int fd = open(_pathname.c_str() , O_RDONLY);
        if(fd < 0)
        {
            ERR_EXIT(" read open: ");
        }    
        else
        {
            int ret = read(fd , buffer , sizeof(buffer)-1);
            if(ret < 0)
            {
                ERR_EXIT("read : ");
            }
            else if( ret == 0 )
            {
                std::cout << "读端读到结尾" << std::endl;
                exit(0);
            }
            else
            {
                buffer[ret] = 0;
            }
        }
        std::cout << buffer << std::endl;
    }

    void Write()
    {
        std::string massage; 
        int fd = open (_pathname.c_str() , O_WRONLY);
        std::getline(std::cin , massage);
        if(fd < 0)
        {
            ERR_EXIT("write open : ");
        }
        else
        {   
            int ret = write(fd , massage.c_str() , massage.size());
            if(ret < 0)
            {
                ERR_EXIT("write : ");
            }
        }
    }

    ~fifo()
    {
        unlink(_pathname.c_str());
        std::cout << "unlink fifo" << std::endl;
    }

private:
    std::string _path;
    std::string _name;
    std::string _pathname;
};